const Controller = require("egg").Controller
const PageModel = require("../model/PageModel");
const MessageBox = require("../utils/MessageBox");
const appConfig = require("../../config/appConfig");
const path = require("path");
const fs = require("fs");
const svgcaptcha = require("svg-captcha");

class CustomerInfoController extends Controller {
    async list() {
        let result = await this.ctx.service.customerInfo.getListByPage(this.ctx.request.query);
        await this.ctx.render("customerInfo/list", {
            customerInfoList: result[0],
            pageModel: new PageModel(result[1][0].totalCount, this.ctx.request.query.pageIndex || 1)
        });
    }

    /**
     * 用户注册
     */
    async register() {
        await this.ctx.render("customerInfo/register");
    }

    async getVCode() {
        let svgData = svgcaptcha.create({
            background:"white"
        });
        this.ctx.session.VCode = svgData.text.toUpperCase();
        this.ctx.response.set("Content-Type", "image/svg+xml");
        this.ctx.body = svgData.data;

    }

    async checkVCode() {
        let vcode = this.ctx.params.vcode;
        this.ctx.body = vcode.toUpperCase() == this.ctx.session.VCode;

    }

    async doRegister() {
        let file = this.ctx.request.files[0];
        if (file) {
            let fileName = Date.now() + file.filename;
            let filePath = path.join(appConfig.customerPhoto, fileName);
            fs.renameSync(file.filepath, filePath);
            this.ctx.request.body.customerphoto = `/customerPhoto/${fileName}`;
        }
        let flag = await this.ctx.service.customerInfo.addCustomerInfo(this.ctx.request.body);
        this.ctx.body = flag;
    }

    async checkCustomerName() {
        let customername = this.ctx.params.customername;
        let result = await this.ctx.service.customerInfo.checkCustomerName(customername);
        this.ctx.body = result ? true : false;
    }

    async login(){
        await this.ctx.render("customerInfo/login");
    }

    async checkLogin(){
        let result = await this.ctx.service.customerInfo.checkLogin(this.ctx.request.body);
        if(result.length==1){
            this.ctx.session.customerInfo=result[0];
            this.ctx.body="登陆成功";
        }
        else{
            this.ctx.body=MessageBox.alertAndBack("用户名或密码错误，请重试");
        }
    }

     //发送邮件
     async sendMail(){
        let mailAddr=this.ctx.params.mailAddr;
        await this.ctx.render("customerInfo/sendMail",{
            mailAddr
        });

    }

    //处理发送邮件的请求
    async doSendMail(){
        this.ctx.body="放松邮件";
    }
}

module.exports = CustomerInfoController;